package com.example.multithread.practise;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/**
 * @ClassName ThreeThread
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2020/5/6 2:07 PM
 * @Version 1.0
 */
public class TwoThread {
	private static final Logger logger = LoggerFactory.getLogger(TwoThread.class);
	private static final Object lock = new char[0];

	public static void main(String[] args) throws InterruptedException {
//		switchThread();
		switchThread2();
		logger.info("不执行吗?");

	}

	private static void switchThread() throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(10);
		new Thread(()-> IntStream.rangeClosed(1, 10).forEach(i -> {
			synchronized (lock) {
				logger.info("Thread A : {}", i);
				lock.notify();
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		})).start();
		Thread.sleep(1000);
		new Thread(()-> IntStream.rangeClosed(1, 10).forEach(i -> {
			synchronized (lock) {
				logger.info("Thread B : {}", i);
				countDownLatch.countDown();
				lock.notify();
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		})).start();
		countDownLatch.await();
	}


	private static void switchThread2() throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(10);
		new Thread(()-> IntStream.rangeClosed(1,5).forEach(i->{

			synchronized (lock) {
				if (countDownLatch.getCount() > 0) {
					logger.info("Thread A : {}", 11 - countDownLatch.getCount());
					countDownLatch.countDown();
					lock.notify();
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		})).start();
		new Thread(()-> IntStream.rangeClosed(1,5).forEach(i-> {
			synchronized (lock) {
				if (countDownLatch.getCount() > 0) {
					logger.info("Thread B : {}", 11 - countDownLatch.getCount());
					countDownLatch.countDown();
					lock.notify();
					try {
						lock.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		})).start();
		countDownLatch.await();
		logger.info(".........不执行吗?");
	}
}
